package de.servicezombie.tcmdb.rest.vo;

import java.io.IOException;
import java.io.StringReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import de.servicezombie.lang.MapUtils;

@XmlRootElement(name = "criteria")
@XmlAccessorType(XmlAccessType.FIELD)
public class WsQueryCriteria extends AbstractWsDomainObject<WsQueryCriteria> {

	/**
	 * needed for REST Framework
	 */
	public static WsQueryCriteria valueOf(String queryCriteriaAsString) {
		WsQueryCriteria qc = new WsQueryCriteria();

		if (queryCriteriaAsString != null) {

			String value = queryCriteriaAsString.replace("::", "\n");
			Properties props = new Properties();

			try {
				props.load(new StringReader(value));
			}
			catch (IOException e) {
				throw new IllegalArgumentException("unable to load query '" + queryCriteriaAsString + "' as properties: "
						+ e.getMessage(), e);
			}

			qc.properties = MapUtils.asMap(props);
		}

		return qc;
	}

	@XmlElement(name = "properties", type = HashMap.class)
	private Map<String, String> properties;

	public Map<String, String> getProperties() {
		properties = MapUtils.emptyMapIfNull(properties);
		return Collections.unmodifiableMap(properties);
	}

	public void add(String property, String value) {
		properties = MapUtils.emptyMapIfNull(properties);
		properties.put(property, value);
	}

}
